package combinatorics;

/**
 * author :  apurv verma
 * email  :  dapurv5@gmail.com
 */

public class Combinations {
	
	private static int n=0;
	private static int r=0;
	private static int column[];
	private static int count=0;
	private static Object C[][];
	public static int nCr=0;
	
	
	public static int factorial(int num){
		int f=1;
		for(int i=1;i<=num;i++){
			f=f*i;
		}
		return f;
	}
	
	/*
	 * RETURNS ALL nCr COMBINATIONS OF THE ELEMENTS OF THE ARRAY A[] 
	 */
	public static Object[][] combinations(Object[] List,int R){
		
		Combinations.n=List.length;
		Combinations.r=R;
		column=new int[n];
		
		nCr=factorial(n)/(factorial(r)*factorial(n-r));
		C=new Object[nCr][r];
		helperCombinations(List,1);
		
		return C;
	}
	
	private static void helperCombinations(Object A[],int k){
		column[k]=column[k-1];
		while(column[k]<n-r+k){
			column[k]=column[k]+1;
			if(k<r)
				helperCombinations(A,k+1);
			else{
				for(int i=1;i<=r;i++){
					//UNCOMMENT TO PRINT ALL COMBINATIONS
					//System.out.print(column[i]);
					C[count][i-1]=A[column[i]-1];
				}
				count++;
				//System.out.println();
			}
		}
	}

	
}
